#!/usr/bin/env python
import sys, os, re
APP_DIR = APP_DIR = os.path.dirname(os.path.abspath(__file__))+'/'

class pluginManager:
    pluginList = []
    pluginMetaData = {}

    def __init__(self):
        directory = APP_DIR +'plugins'
        i = 0
        sys.path.insert(0, directory)

        for fn in os.listdir(directory):
            if fn[-3:] == ".py":
                mod = fn[:-3]
                try:
                    self.pluginMetaData[mod] = self.parseMetaData(fn)
                    pl = __import__(mod)
                    exec("self.pluginList.append(pl."+pl.__name__+"())")    
                except Exception, (strerror):
                    print 'Error loading plugin "'+mod+'": % s' % (strerror)

    def parseMetaData(self, filename):
        metaData = {}        
        metaDataFound = False

        fileHandle = open(APP_DIR+'plugins/'+filename) 
        a = fileHandle.readline()
        while (a!=''):
            if (a.find('/pluginDescription')>-1):
                break
            if (a.find('pluginDescription')>-1):
                metaDataFound = True
            m = re.match('^#\s+@(\S+)\s+([^\n]+)$', a)
            if (m):
                metaData[m.group(1)] = m.group(2)
            a = fileHandle.readline()
        fileHandle.close()

        if (metaDataFound == False):
            print 'No metadata found for plugin '+filename
            metaData['name'] = filename
        return metaData                 

    def executePluginAction(self, actionName, paramList = []):
        p = []     
        paramList_str = ''
        i = 0;
        for param in paramList:
            p.append(param)
            paramList_str = '%s p[%i], ' % (paramList_str, i)
            i = i+1;

        for plugin in self.pluginList:
            try:
                exec("plugin."+actionName+"("+paramList_str+")")
            except Exception, (strerror):
                print 'Error with plugin "'+plugin.__class__.__name__+'": % s' % (strerror)
        return


